package com.wang.data.server;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wang.data.repository.F2Interface;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
@Component
@Sharable 
public class NettyServerHandler extends SimpleChannelInboundHandler<String> {
	private final LinkedBlockingDeque<String> queue;
	private boolean isStop = false;
	@Autowired
    private F2Interface repository;
	NettyServerHandler() {
		System.out.println("NettyServerHandler init");
		queue = new LinkedBlockingDeque<String>();
		MyConsumer con = new MyConsumer();
		con.start();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		System.out.println("server read Message: " + msg);
		queue.add(msg);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		String clientIp = insocket.getAddress().getHostAddress();
		System.out.println("收到客户端[ip:" + clientIp + "]连接");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		// 当出现异常就关闭连接
		ctx.close();
	}

	class MyConsumer extends Thread {

		@Override
		public void run() {
			System.out.println("consumer is working....");
			List<String> list = new ArrayList<String>();
			while (!isStop) {
				try {
					

					if (list.size() >= 1000) {
						String sql = buildSql(list);
						System.out.println(sql);
						repository.insert(sql);
						
						list.clear();
					} else {
						String item = queue.take();
						list.add(item);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

	private String buildSql(List<String> list) {
		StringBuilder sb = new StringBuilder();
		//sb.append("insert into f2 values");
		list.forEach(l -> {
			sb.append("('");
			sb.append(l);
			sb.append("',");
			sb.append("now()");
			sb.append("),");

		});
		return sb.substring(0, sb.lastIndexOf(","));
	}
}
